package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/7/27 下午4:36
 */
public class RpcClientProxy {

    public static final List<RpcClient> clients = new ArrayList<>(3);

    static {
        clients.add(new RpcClient("127.0.0.1", 8897));
        clients.add(new RpcClient("127.0.0.1", 8898));
        clients.add(new RpcClient("127.0.0.1", 8899));
    }
    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(serviceClass.getClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        System.out.println("发送的消息为:" + rpcRequest.toString());
                        //2.创建RpcClient对象
                        RpcClient rpcClient = roundClient();
                        System.out.println(rpcClient);
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            System.out.println("发送消息的结果为: " + rpcResponse.toString());
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        }
                    }
                });
    }

    public static int clientIndex = 0;

    /**
     * 轮询获取Client
     * @return
     */
    private static RpcClient roundClient(){
        if(clientIndex >= clients.size()){
            clientIndex %= clients.size();
        }
        return clients.get(clientIndex++);
    }
}
